package extend;

import io.ebean.config.DatabaseConfig;
import io.ebean.config.PropertiesWrapper;
import io.ebeaninternal.dbmigration.DefaultDbMigration;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * 处理ide内直接点击运行working dir问题
 */
public final class MyDbMigration extends DefaultDbMigration {
  private final static String PATH_TO_RESOURCES = "migration.pathToResources";

  @Override
  public void setServerConfig(DatabaseConfig config) {
    Properties properties = config.getProperties();
    if (properties != null) {
      PropertiesWrapper props = new PropertiesWrapper("ebean", config.getName(), properties, null);
      pathToResources = props.get(PATH_TO_RESOURCES, pathToResources);
      File file = new File(pathToResources);
      if (!file.exists()) {
        String current = new File("").getAbsolutePath();
        String root = current.replace("/common/ebean-generator", "");
        Path p1 = Paths.get(root, pathToResources);
        Path p2 = Paths.get(current);
        pathToResources = p2.relativize(p1).toString();
        config.getProperties().setProperty("ebean." + PATH_TO_RESOURCES, pathToResources);
      }
    }
    super.setServerConfig(config);
  }
}
